import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useRef } from 'react';
import { ContractManageAPI } from '../common/type';
import { Col, DatePicker, Form, Input, Row, Spin, message } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import moment from 'moment';
import { UploadFormCommon } from '@/components/UploadForm';
import { onCloseModalCommon } from '@/utils';
import { addProcessService, finishProcessService } from '../services';
import { ConractControllerContext } from '../common';

export const OpenProcessUpdateModal: React.FC<ContractManageAPI.IOpenProcessUpdateModal> = ({ onClose, selectRowInfo, reloadManage }) => {
  /** 弹框Ref */
  const processNodeModalRef: Ref<IOneModalRef> = useRef(null);

  /** 引入上下文 */
  const {
    locationState: { pIDDetailInfo },
  } = useContext(ConractControllerContext);

  /** 表单 */
  const [processForm] = Form.useForm();

  /** 初始化数据 */
  useEffect(() => {
    if (selectRowInfo?.id) {
      processForm?.setFieldsValue({
        ...selectRowInfo,
        payTime: selectRowInfo?.payTime ? moment(selectRowInfo?.payTime) : null,
        lastPayTime: selectRowInfo?.lastPayTime ? moment(selectRowInfo?.lastPayTime) : null,
      });
    }
  }, [selectRowInfo]);

  /** 接口调用回调 */
  const callback = (res) => {
    if (res && res?.msgFlag) {
      onCloseModalCommon(processNodeModalRef);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入编辑完成接口 */
  const { finishProcessRun, finishProcessLoading } = finishProcessService(callback);

  /** 引入添加接口 */
  const { addProcessLoading, addProcessRun } = addProcessService(callback);

  /** 点击确定 */
  const onSave = () => {
    processForm?.validateFields()?.then((values: any) => {
      const payload: Record<string, any> = {
        ...values,
        payFlag: '0',
      };

      if (selectRowInfo?.id) {
        const editPayload: Record<string, any> = {
          ...payload,
          id: selectRowInfo.id,
          versionNum: selectRowInfo.versionNum,
          payState: 3,
          lastPayTime: values?.lastPayTime ? moment(values?.lastPayTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
        };
        finishProcessRun(editPayload);
      } else {
        const addPayload: Record<string, any> = {
          ...payload,
          payState: '0',
          payType: '5',
          contractID: pIDDetailInfo?.id,
          paySum: 0,
          payTime: values?.payTime ? moment(values?.payTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
        };
        addProcessRun(addPayload);
      }
    });
  };

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={processNodeModalRef}
      title={selectRowInfo?.id ? '确认完成' : ' 添加履约记录'}
      width={document.body.clientWidth * 0.35}
      onCancel={onClose}
      bodyStyle={{
        padding: '5px 10px',
      }}
      onOk={onSave}
      confirmLoading={finishProcessLoading || addProcessLoading}
    >
      <Spin spinning={finishProcessLoading || addProcessLoading}>
        <div className={pageStyles['fromView-styles']}>
          <Form form={processForm}>
            <Row>
              {selectRowInfo?.id ? (
                <>
                  <Col span={24}>
                    <Form.Item
                      label="完成情况说明"
                      name="finishExplain"
                      rules={[
                        {
                          required: true,
                          message: '请输入完成情况说明',
                        },
                      ]}
                    >
                      <Input.TextArea allowClear showCount maxLength={500} placeholder="请输入" autoSize={{ minRows: 4, maxRows: 8 }} />
                    </Form.Item>
                  </Col>
                  <UploadFormCommon
                    form={processForm}
                    label="佐证材料"
                    fileFormName={'attachURL'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={true}
                    accept={'.jpg|.png|.jpeg|.pdf'}
                    url={'/contractController/uploadFile'}
                    downloadUrl={'/contractController/downloadFile'}
                    fileFormDelName={'attachURLDEL'}
                    delFunc={() => {}}
                    maxFile={5}
                    defaultFiles={selectRowInfo && selectRowInfo?.id ? selectRowInfo?.attachURL : null}
                    fieldBusiPath={'contract/info'}
                    // onOpenReadOfdWord={onOpenReadOfdWord}
                  >
                    上传
                  </UploadFormCommon>
                  <Col span={24}>
                    <Form.Item
                      label="完成时间"
                      name="lastPayTime"
                      rules={[
                        {
                          required: true,
                          message: '请选择完成时间',
                        },
                      ]}
                    >
                      <DatePicker
                        placeholder="请选择"
                        style={{ width: '100%' }}
                        format="YYYY-MM-DD"
                        disabledDate={(currentDate: any) => {
                          return currentDate && currentDate < moment();
                        }}
                      />
                    </Form.Item>
                  </Col>
                </>
              ) : (
                <>
                  <Col span={24}>
                    <Form.Item
                      label="预期时间"
                      name="payTime"
                      rules={[
                        {
                          required: true,
                          message: '请选择预期时间',
                        },
                      ]}
                    >
                      <DatePicker
                        placeholder="请选择"
                        style={{ width: '100%' }}
                        format="YYYY-MM-DD"
                        disabledDate={(currentDate: any) => {
                          return currentDate && currentDate < moment();
                        }}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      label="履约事项"
                      name="payExplain"
                      rules={[
                        {
                          required: true,
                          message: '请输入履约事项',
                        },
                      ]}
                    >
                      <Input.TextArea allowClear showCount maxLength={500} placeholder="请输入" autoSize={{ minRows: 4, maxRows: 8 }} />
                    </Form.Item>
                  </Col>
                </>
              )}
            </Row>
          </Form>
        </div>
      </Spin>
    </OneModal>
  );
};
